<template>
  <div>
    <el-form
        ref="dataManageForm"
        :model="dataForm"
        label-width="80px"
        class="dataFormStyle">
      <template v-for="(item, index) in dataForm" :key="index">
        <el-form-item :prop="index+'.fieldValue'"
                      :rules="item.fieldRule"
                      class="dataFormItemStyle">
          <template slot="label">
            <el-tooltip effect="light" :content="item.fieldTitle" placement="top">
              <div class="elFormItemLabelLongText">{{ item.fieldTitle }}</div>
            </el-tooltip>
          </template>
          <el-input
              id="formItemInput"
              v-if="item.dataType !== 2 && index === 0"
              v-model="item.fieldValue"
              :placeholder="'请输入'+item.fieldTitle"
              spellcheck ="false"
              @blur="blurValid(index+'.fieldValue')">
          </el-input>
          <el-input
              v-if="item.dataType !== 2 && index !== 0"
              v-model="item.fieldValue"
              :placeholder="'请输入'+item.fieldTitle"
              spellcheck ="false"
              @blur="blurValid(index+'.fieldValue')">
          </el-input>
          <el-date-picker
              v-if="item.dataType === 2"
              v-model="item.fieldValue"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期"
              @change="blurValid(index+'.fieldValue')">
          </el-date-picker>
        </el-form-item>
      </template>
    </el-form>
  </div>
</template>

<script>
import {inforesApi} from "../../../api/irpApi";

export default {
  data() {
    return {
      //当前处理类型，0新建  1编辑
      curProcessType: 0,
      //编辑操作的原数据
      originalModifyValue:{},
      dataForm: [],
      dataFormFB: [],
      resGuid: '',
      PKFieldNames:[]
    }
  },
  methods: {
    isObjectEmpty: function (obj) {
      // 检查对象是否为空对象
      if (Object.keys(obj).length === 0 && obj.constructor === Object) {
        return true;
      }

      // 遍历对象的所有属性
      for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
          const value = obj[key];
          if (value) {
            const fieldValue = value.fieldValue
            // 判断属性值是否为空。这里定义为空为 null, undefined 或空字符串。
            if (fieldValue !== null && fieldValue !== undefined && fieldValue !== "") {
              return false;
            }
          }
        }
      }

      // 如果所有属性值都为空，则返回 true
      return true;
    },
    dataManageCallback: function (v1, callBack) {
      //编辑操作强制修改主键，补充校验
      if (!this.isPKNotChange()){
        let dataFormPKFields = this.dataForm.filter(processItem => {
          return this.PKFieldNames.includes(processItem.fieldName);
        })
        for (let dataFormPKField of dataFormPKFields) {
          let primaryKeyRule = this.primaryKeyRuleFactory(this,dataFormPKField.fieldName)
          dataFormPKField.fieldRule.push(primaryKeyRule)
        }
      }
      this.$refs['dataManageForm'].validate((valid) => {
        if (valid) {
          if (this.curProcessType === 0) {

            //特殊字段值转换
            this.fieldValueConversion(this.dataForm)

            if (this.isObjectEmpty(this.dataForm)) {
              callBack(false)
              this.$BI.Dialog.error('所有字段值均为空，不允许创建');
            } else {
              inforesApi.dataManageAddData(this.resGuid, {'addDataArr': this.dataForm}).then((res) => {
                if (res.processSuccess)
                  callBack(res.addItem)
                else {
                  this.$BI.Dialog.error(res.errorInfo);
                  callBack(false)
                }
              })
            }
          } else {

            //特殊字段值转换
            this.fieldValueConversion(this.dataForm)
            let originalModifyValue = this.originalModifyValue

            if (this.isObjectEmpty(this.dataForm)) {
              callBack(false)
              this.$BI.Dialog.error('所有字段值均为空，不允许修改');

            } else if (this.PKFieldNames.length > 0  && this.isPKNotChange()){
              inforesApi.dataManageModifyDataByPK(this.resGuid, {'modifyDataArr': this.dataForm}).then((res) => {
                if (res.processSuccess){
                  let transItem = {
                    modifyItem : res.modifyItem,
                    originalModifyValue : originalModifyValue
                  }
                  callBack(JSON.stringify(transItem))
                }
                else {
                  this.$BI.Dialog.error(res.errorInfo);
                  callBack(false)
                }
              });
            } else {
              let modifyParam = {
                'oldDataArr': this.dataFormFB,
                'curDataArr': this.dataForm
              }
              inforesApi.dataManageModifyDataByAllFields(this.resGuid, modifyParam).then((res) => {
                if (res.processSuccess){
                  let transItem = {
                    modifyItem : res.modifyItem,
                    originalModifyValue : originalModifyValue
                  }
                  callBack(JSON.stringify(transItem))
                }
                else {
                  this.$BI.Dialog.error(res.errorInfo);
                  callBack(false)
                }
              });
            }
          }

        } else {
          callBack(false)
        }
      });
    },
    isPKNotChange:function () {
      let dataFormPKFields = this.dataForm.filter(processItem => {
        return this.PKFieldNames.includes(processItem.fieldName);
      })
      let dataFormFBPKFields= this.dataFormFB.filter(processItem => {
        return this.PKFieldNames.includes(processItem.fieldName);
      })

      for (let i = 0; i < dataFormFBPKFields.length; i++) {
        if (dataFormPKFields[i].fieldValue !== dataFormFBPKFields[i].fieldValue)
          return false
      }
      return true
    },
    fieldValueConversion:function (targetArr) {
      for (let targetItem of targetArr){
        console.log("布尔值转换")
        //布尔类型
        if (targetItem.dataType === 1){
           if (targetItem.fieldValue === '是' || targetItem.fieldValue.toLowerCase() === 'true' || /^-?\d+$/.test(targetItem.fieldValue) && targetItem.fieldValue > 0)
             targetItem.fieldValue = '1'
           else if (targetItem.fieldValue === '否' || targetItem.fieldValue.toLowerCase() === 'false' || /^-?\d+$/.test(targetItem.fieldValue) && targetItem.fieldValue <= 0)
              targetItem.fieldValue = '0'
        }
      }
    },
    //动态装配的校验项
    //主键唯一校验
    primaryKeyRuleFactory: (_this,fieldName) => ({
      validator: (rule, value, callback) => {
        if (value === '' || value === null || value === undefined) {
          callback()
        }else {
          let primaryKeyFieldArr = _this.dataForm.filter(processItem => {
            return _this.PKFieldNames.includes(processItem.fieldName);
          })

          inforesApi.dataManageValidPrimaryKey(_this.resGuid, {'primaryKeyFieldArr': primaryKeyFieldArr}).then((res) => {
            if (res.processSuccess)
              if (res.checkPass){
                callback()
              }else {
                let primaryKeyField = primaryKeyFieldArr.filter(processItem => {
                  return processItem.fieldName === fieldName;
                })
                callback(new Error(`主键值【${primaryKeyField[0].fieldValue}】已存在`))
              }
            else {
              callback(new Error(res.errorInfo))
            }
          })
        }
      },
      trigger: 'blur'
    }),
    //非空校验
    requiredRuleFactory: () => ({
      required: true, message: '当前字段不能为空', trigger: 'blur'
    }),
    //精度(长度)校验
    precisionRuleFactory: (precision) => ({
      validator: (rule, value, callback) => {
        if (value === '' || precision === 0 || value === null || value === undefined) {
          callback();
        }else {
          if (value.length > precision) {
            callback(new Error(`输入数据长度不能大于${precision}`));
          } else {
            callback();
          }
        }
      },
      trigger: 'blur'
    }),
    //小数位校验
    decimalCountRuleFactory: (decimalCount) => ({
      validator: (rule, value, callback) => {
        if (value === '' || value === null || value === undefined) {
          callback();
        }else {
          let index = value.indexOf('.');
          if (!/^\d+(\.\d+)?$/.test(value)) {
            callback(new Error('只能输入浮点型数据!'));
          } else if (index > 0 && value.substr(index + 1, value.length).length > decimalCount) {
            callback(new Error(`小数位不能多于${decimalCount}位!`));
          } else {
            callback();
          }
        }
      },
      trigger: 'blur'
    }),
    //整型、长整型校验
    integerTypeRuleFactory: () => ({
      validator: (rule, value, callback) => {
        if (value === '' || value === null || value === undefined) {
          callback();
        }else {
          if (!/^[0-9]*$/.test(value)) {
            callback(new Error('只能输入整型数据!'));
          } else {
            callback();
          }
        }
      },
      trigger: 'blur'
    }),
    //布尔类型校验
    booleanTypeRuleFactory: () => ({
      validator: (rule, value, callback) => {
        if (value === '' || value === null || value === undefined) {
          callback();
        }else {
          if (value.toLowerCase() !== 'true'
              && value.toLowerCase() !== 'false'
              && value !== '是'
              && value !== '否'
              && !/^-?\d+$/.test(value)) {
            callback(new Error('请输入true、false、是、否或数值（大于0代表true）！'));
          } else {
            callback();
          }
        }
      },
      trigger: 'blur'
    }),
    blurValid: function (propName) {
      this.$refs['dataManageForm'].validateField(propName, () => {
      })
    },
    addAndModifyBaseInit:function(fatherComponentProps) {
      //当前弹框处理类型
      this.curProcessType = fatherComponentProps.curProcessType

      //设置资源guid
      this.resGuid = fatherComponentProps.resGuid

      //设置主键字段名称数组
      this.PKFieldNames=JSON.parse(JSON.stringify(fatherComponentProps.curTablePKNameArr))

      //设置表单数据
      this.dataForm.splice(0, this.dataForm.length)
      let filedInfos = fatherComponentProps.filedInfos
      for (let i = 0; i <= filedInfos.length - 1; i++) {
        var newObj = {
          fieldName: filedInfos[i].prop,
          fieldTitle: filedInfos[i].title,
          fieldValue: '',

          //动态字段添加校验
          fieldRule: [],
          //数据类型
          dataType: 0
        };
        this.dataForm.push(newObj);
      }

      //默认聚焦表单第一个input框
      //注意两点：
      // ①input是通过遍历dataForm得来的，只有datafrom有值了才会渲染input dom元素
      // ②vue渲染是异步的，刚把dataForm的值组建好，立刻去查询input dom,此时未必已经渲染完毕
      this.$nextTick(() => {
        const inputElement = document.querySelector('#formItemInput');
        if (inputElement) inputElement.focus()
      });
    },
    setValidRules:function(curStructure, curDataFormItem) {
      if (curStructure.isPrimaryKey && this.curProcessType === 0){
        let primaryKeyRule = this.primaryKeyRuleFactory(this,curDataFormItem.fieldName)
        curDataFormItem.fieldRule.push(primaryKeyRule)
      }
      if (curStructure.isNotNull) {
        let requiredRule = this.requiredRuleFactory()
        curDataFormItem.fieldRule.push(requiredRule)
      }
      if (curStructure.precision !== "") {
        let curFieldPrecision = curStructure.precision - 0
        let precisionRule = this.precisionRuleFactory(curFieldPrecision);
        //对于布尔类型不校验精度
        if (curStructure.dataType !== 1) curDataFormItem.fieldRule.push(precisionRule);
      }

      //BOOLEAN 类型校验输入内容
      if (curStructure.dataType === 1) {
        let booleanTypeRule = this.booleanTypeRuleFactory()
        curDataFormItem.fieldRule.push(booleanTypeRule)
      }
      //DOUBLE 类型校验小数位
      if (curStructure.dataType === 3) {
        let decimalCount = curStructure.scale - 0
        let decimalCountRule = this.decimalCountRuleFactory(decimalCount);
        curDataFormItem.fieldRule.push(decimalCountRule);
      }
      //INTEGER LONG 类型校验输入内容
      if (curStructure.dataType === 5 || curStructure.dataType === 8) {
        let integerTypeRule = this.integerTypeRuleFactory()
        curDataFormItem.fieldRule.push(integerTypeRule)
      }
    },
    processTableStructureInfo:function() {
      let _this = this
      return new Promise(resolve => {
        inforesApi.getStructureTabData({"resGuid": this.resGuid}).then((res) => {
          for (let i = 0; i < res.data.structure.length; i++) {
            let curStructure = res.data.structure[i];
            let curDataFormItem = _this.dataForm.find(processItem => {
              return processItem.fieldName === curStructure.fieldName
            })
            //设置表单校验规则
            _this.setValidRules(curStructure, curDataFormItem);

            //设置表单项数据类型
            curDataFormItem.dataType = curStructure.dataType;
          }
          resolve()
        })
      })
    },
  },
  mounted() {
    let dialogId = this.$route.params.dialogId;
    let fatherComponentProps = this.$BiTopWin.$.bi.ui.getFrameDialogValues(dialogId);

    this.addAndModifyBaseInit(fatherComponentProps);

    this.processTableStructureInfo()
        .then(() => {
          if (this.curProcessType === 1) {
            this.originalModifyValue = fatherComponentProps.curSelectedItem
            let modifyItem = fatherComponentProps.curSelectedItem

            for (const formItem of this.dataForm) {
              formItem.fieldValue = modifyItem[formItem.fieldName]
            }
            this.dataFormFB = JSON.parse(JSON.stringify(this.dataForm));
          }
        });

    window.confirmHandle = this.dataManageCallback;
  }
}

</script>

<style scoped>
.dataFormStyle {
  display: flex;
  flex-direction: column;
  justify-content: center;
  margin: 35px;
}

.dataFormItemStyle > :first-child {
  display: flex;
  justify-content: flex-end;
}

.elFormItemLabelLongText {
  width: auto;

  font-family: PingFangSC-Regular;
  font-weight: 400;
  font-size: 14px;
  color: #424242;

  overflow: hidden; /* 隐藏超出容量的文本 */
  white-space: nowrap; /* 确保文本不会换行 */
  text-overflow: ellipsis; /* 显示省略号 */
}
</style>
